<?php
namespace app\services;

use app\api\model\Type;
use app\move\model\Goods;

class GoodsServices
{
   public static function goodsList($param)
   {
       $limit = isset($param['limit'])?$param['limit']:config('setting.goodLimit');
       if (!is_numeric($limit)) {
           abort(2001,'每页显示的数量只能是数字');
       }
       $page =  isset($param['limit'])?$param['limit']:1;
       if (!is_numeric($page)) {
           abort(2001,'页码只能是数字');
       }

       # 搜索条件
       # 组装条件
       $where = [];
       # 1 商品名称
       if (isset($param['goods_name']) && !empty($param['goods_name'])) {
           $where[] = [
               'goods_name','like',"%{$param['goods_name']}%"
           ];
       }
       # 商品状态 上架/下架
       if (
           isset($param['is_on_sale']) &&  //请求参数中是否传递该参数
           $param['is_on_sale'] != '' &&  // 该参数是否为空
           (in_array($param['is_on_sale'],[0,1]))// 该参数是否在0/1之间
       ){
           $where[] = [
               'is_on_sale','=',$param['is_on_sale']
           ];
       }

       # 区间搜索
       if (
           isset($param['max_price']) && is_numeric($param['max_price']) &&
           isset($param['min_price']) && is_numeric($param['min_price'])
       ) {
           # 当我最大值小于最小值的时候、怎么办？两个值互换
           if ($param['max_price'] < $param['min_price']) {

               list($param['max_price'],$param['min_price']) = [$param['min_price'],$param['max_price']];
           }

           $where[] = [
               'goods_price', '<',$param['max_price']
           ];
           $where[] = [
               'goods_price', '>',$param['min_price']
           ];
       }
       # 列表结果排序
       # 排序字段的集合
       $sort_field_set = [
           'goods_price',
           'sales_num'
       ];
       $sort_style_set= ['desc','asc'];// 排序的方式
       if (
           isset($param['sort_field']) && in_array($param['sort_field'],$sort_field_set) &&
           isset($param['sort_style']) && in_array($param['sort_style'],$sort_style_set)
       ) {
           $sort_field = $param['sort_field'];// 排序的字段
           $sort_style = $param['sort_style'];// 降序/还是升序
       } else {
           # 默认按照价格升序排序
           $sort_field = $sort_field_set[0];
           $sort_style = $sort_style_set[1];// 降序/还是升序
       }
        echo $sort_field,$sort_style;
//       dd($limit);
       $data = \app\api\model\Goods::where($where)->with(['cate','brand','images'])->order($sort_field,$sort_style)->paginate([
           'list_row'=>$limit,
           'query'=>$param
       ]);

       $data = empty($data) ? [] : $data->toArray();
       return $data;
   }


}
